package com.equdao.car_violation_inquiry.handler;

import com.equdao.car_violation_inquiry.exception.NotFindTokenException;
import com.equdao.car_violation_inquiry.exception.ViolationException;
import com.equdao.car_violation_inquiry.pojo.Result;
import com.equdao.car_violation_inquiry.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: 杨忠强
 * @Date: 2018/7/19 16:13
 * @Description:
 */

@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    public static final String DEFAULT_ERROR_VIEW = "error";


    /**
     * 捕获全局异常,防止返回500错误码
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof ViolationException) {
            //捕获自定义异常
            return ResultUtil.error(1, "传输参数有误");
        }else {
            logger.error("[系统异常] {}",e);
            return ResultUtil.error(99, "未知错误");
        }


    }



    @ExceptionHandler(value = NotFindTokenException.class)
    //@ResponseStatus(HttpStatus.HTTP_VERSION_NOT_SUPPORTED.ACCEPTED)  设置返回的响应吗
    public ModelAndView handleNotFindTokenException(HttpServletRequest request, Exception e) {
        ModelAndView view = new ModelAndView();

        view.addObject("url",request.getRequestURL());
        view.setViewName(DEFAULT_ERROR_VIEW);

        //跳转登录页面
        System.out.println("跳转登录");

          return view;



    }

}
